//
//  YCAppScoreAlert.m
//  AppScoreAlertView
//
//  Created by 唐可雄 on 16/9/20.
//  Copyright © 2016年 swustyc. All rights reserved.
//

#import "YCAppScoreAlert.h"

#import <UIKit/UIKit.h>

#define kUserDefault_AppScoreAlert  @"_YC_AppScoreAlert"
#define kUserDefault_AppScoreAlert_Last @"lastTime"
/// 0表示不提示，1表示提示
#define kUserDefault_AppScoreAlert_type @"type"
#define kUserDefault_AppScoreAlert_Version  @"version"

#define kAlert_LaterOn 2*24*60*60

#define kAlert_YES  1
#define kAlert_NO   0

static NSString *appId = nil;
static YCAppScoreAlert *manager = nil;

@interface YCAppScoreAlert ()<UIAlertViewDelegate>

/**
 Apple Id，itunes connect给应用分配的数字序列号
 */
@property (copy, nonatomic) NSString *appId;

@end

@implementation YCAppScoreAlert

+ (void)load {
    [super load];
    
    [[NSNotificationCenter defaultCenter] addObserver:[YCAppScoreAlert sharedInstance] selector:@selector(judgeToShow) name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Public Methods

+ (void)setAppId:(NSString *)appId {
    [YCAppScoreAlert sharedInstance].appId = appId;
}

#pragma mark - Private Methods

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[YCAppScoreAlert alloc] init];
    });
    
    return manager;
}

- (void)configAlertLaterOn {
    [[NSUserDefaults standardUserDefaults] setValue:@{kUserDefault_AppScoreAlert_Last:@([[NSDate date] timeIntervalSince1970]),
                                                      kUserDefault_AppScoreAlert_type:@(kAlert_YES),
                                                      kUserDefault_AppScoreAlert_Version:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]}
                                             forKey:kUserDefault_AppScoreAlert];
}

- (void)configAlertNO {
    [[NSUserDefaults standardUserDefaults] setValue:@{kUserDefault_AppScoreAlert_Last:@([[NSDate date] timeIntervalSince1970]),
                                                      kUserDefault_AppScoreAlert_type:@(kAlert_NO),
                                                      kUserDefault_AppScoreAlert_Version:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]}
                                             forKey:kUserDefault_AppScoreAlert];
}

/**
 判断是否展示对话框
 */
- (void)judgeToShow {
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] valueForKey:kUserDefault_AppScoreAlert];
    if (dic == nil) {
        // 没有展示过对话框，将当前时间保存下来
        [self configAlertLaterOn];
    } else {
        if ([dic[kUserDefault_AppScoreAlert_Version] isEqualToString:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]]) {
            if ([dic[kUserDefault_AppScoreAlert_type] integerValue] == kAlert_YES) {
                // 展示过对话框，判断当前时间距离上次记录多久了
                long long lastTime = [dic[kUserDefault_AppScoreAlert_Last] longLongValue];
                NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:[NSDate dateWithTimeIntervalSince1970:lastTime]];
                if (interval > kAlert_LaterOn) {
                    [self showAlert];
                }
            }
        } else {
            [self configAlertLaterOn];
        }
    }
}

/**
 展示评分提醒对话框
 */
- (void)showAlert {
    NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
    if (appName == nil) {
        appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
    }
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"评价%@", appName] message:[NSString stringWithFormat:@"感谢您陪伴%@成长的每一天，给我们留言吧，我们会努力做的更好！", appName] delegate:[YCAppScoreAlert sharedInstance] cancelButtonTitle:@"不，谢谢" otherButtonTitles:@"去评价", @"稍后提醒", nil];
    [alert show];
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // 不，谢谢
        [self configAlertNO];
    } else if (buttonIndex == 1) {
        // 去评价
        NSString *baseUrl = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@", self.appId];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:baseUrl]];
        
        [self configAlertNO];
    } else {
        // 稍后再说
        [self configAlertLaterOn];
    }
}

@end
